package myapp;

import javax.servlet.http.Cookie;

import net.jforum.ControllerUtils;
import net.jforum.JForumExecutionContext;
import net.jforum.context.RequestContext;
import net.jforum.context.SessionContext;
import net.jforum.entities.UserSession;
import net.jforum.sso.SSO;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

//
// foruma kullanici giris cikislari bu class tarafindan kontrol ediliyor
public class MySSO implements SSO {

	public String authenticateUser(RequestContext request) {
		//
		// bizim sistemden gonderilen login cookieleri aliniyor
		// username jforum database'inde yoksa alinan email, password bilgileri
		// de kullanilarak otomatik olarak yeni bir kullanici yaratilacak
		Cookie myCookie = ControllerUtils.getCookie(SystemGlobals
				.getValue(ConfigKeys.COOKIE_NAME_USER));
		String username = null;
		String email = null;
		String password = null;

		if (myCookie != null) {
			username = myCookie.getValue();
		}
		SessionContext session = JForumExecutionContext.getRequest().getSessionContext();

		// email bilgisi iceren cookie
		myCookie = ControllerUtils.getCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_EMAIL));
		if (myCookie != null) {
			email = myCookie.getValue();
			session.setAttribute(SystemGlobals.getValue(ConfigKeys.SSO_EMAIL_ATTRIBUTE), email);
		}
		// sifre bilgisi iceren cookie
		myCookie = ControllerUtils.getCookie(SystemGlobals
				.getValue(ConfigKeys.COOKIE_NAME_PASSWORD));
		if (myCookie != null) {
			password = myCookie.getValue();
			session.setAttribute(SystemGlobals.getValue(ConfigKeys.SSO_PASSWORD_ATTRIBUTE),
					password);
		}

		return username; // jforum username
	}

	public boolean isSessionValid(UserSession userSession, RequestContext request) {
		Cookie SSOCookie = ControllerUtils.getCookie(SystemGlobals
				.getValue(ConfigKeys.COOKIE_NAME_USER));
		String remoteUser = null;

		if (SSOCookie == null) {
			return false;
		} else {

			// removeCookies fonksiyonu butun cookielerin maxAge'ini 0 yapmisti
			// yani kullanici logout yapti, session invalid
			if (SSOCookie.getMaxAge() == 0) {
				return false;
			}

			remoteUser = SSOCookie.getValue(); // jforum username
		}

		// user has since logged out
		if (remoteUser == null
				&& userSession.getUserId() != SystemGlobals
						.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
			return false;
			// user has since logged in
		} else if (remoteUser != null
				&& userSession.getUserId() == SystemGlobals
						.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
			return false;
			// user has changed user
		} else if (remoteUser != null && !remoteUser.equals(userSession.getUsername())) {
			return false;
		}
		return true; // myapp user and forum user the same
	}

}
